import requests
import json

print("===== 全面CORS配置测试 =====\n")

base_url = "http://localhost:8001"

# 测试场景1: 简单GET请求，带Origin头
def test_simple_get():
    print("\n[场景1] 测试简单GET请求，带Origin头")
    try:
        headers = {
            "Origin": "http://example.com",  # 模拟跨域来源
            "Accept": "application/json"
        }
        response = requests.get(f"{base_url}/", headers=headers)
        print(f"状态码: {response.status_code}")
        print("响应头:")
        for key, value in response.headers.items():
            if "Access-Control" in key:
                print(f"  {key}: {value}")
        
        # 检查是否存在关键CORS头
        has_allow_origin = "Access-Control-Allow-Origin" in response.headers
        has_allow_credentials = "Access-Control-Allow-Credentials" in response.headers
        
        print(f"\n结果: {'通过' if has_allow_origin else '失败'} - {'包含' if has_allow_origin else '缺失'} Access-Control-Allow-Origin")
        print(f"结果: {'通过' if has_allow_credentials else '失败'} - {'包含' if has_allow_credentials else '缺失'} Access-Control-Allow-Credentials")
        
    except Exception as e:
        print(f"请求错误: {e}")

# 测试场景2: 预检OPTIONS请求
def test_options_preflight():
    print("\n[场景2] 测试预检OPTIONS请求")
    try:
        headers = {
            "Origin": "http://example.com",
            "Access-Control-Request-Method": "POST",
            "Access-Control-Request-Headers": "Content-Type, Authorization"
        }
        response = requests.options(f"{base_url}/", headers=headers)
        print(f"状态码: {response.status_code}")
        print("响应头:")
        for key, value in response.headers.items():
            if "Access-Control" in key:
                print(f"  {key}: {value}")
        
        # 检查是否存在所有必要的CORS头
        has_allow_origin = "Access-Control-Allow-Origin" in response.headers
        has_allow_methods = "Access-Control-Allow-Methods" in response.headers
        has_allow_headers = "Access-Control-Allow-Headers" in response.headers
        has_max_age = "Access-Control-Max-Age" in response.headers
        
        print(f"\n结果: {'通过' if has_allow_origin else '失败'} - {'包含' if has_allow_origin else '缺失'} Access-Control-Allow-Origin")
        print(f"结果: {'通过' if has_allow_methods else '失败'} - {'包含' if has_allow_methods else '缺失'} Access-Control-Allow-Methods")
        print(f"结果: {'通过' if has_allow_headers else '失败'} - {'包含' if has_allow_headers else '缺失'} Access-Control-Allow-Headers")
        print(f"结果: {'通过' if has_max_age else '失败'} - {'包含' if has_max_age else '缺失'} Access-Control-Max-Age")
        
    except Exception as e:
        print(f"请求错误: {e}")

# 测试场景3: 带凭证的请求
def test_credentials():
    print("\n[场景3] 测试带凭证的请求")
    try:
        headers = {
            "Origin": "http://example.com",
            "Accept": "application/json"
        }
        # 发送带cookies的请求
        response = requests.get(f"{base_url}/", headers=headers, cookies={"test": "value"})
        print(f"状态码: {response.status_code}")
        print("响应头:")
        for key, value in response.headers.items():
            if "Access-Control" in key:
                print(f"  {key}: {value}")
        
        # 检查Access-Control-Allow-Credentials是否设置为true
        allow_credentials = response.headers.get("Access-Control-Allow-Credentials", "")
        has_correct_credentials = allow_credentials.lower() == "true"
        
        print(f"\n结果: {'通过' if has_correct_credentials else '失败'} - Access-Control-Allow-Credentials {'正确设置为true' if has_correct_credentials else '未设置为true'}")
        
    except Exception as e:
        print(f"请求错误: {e}")

# 测试场景4: 测试不同路径的CORS响应
def test_different_paths():
    print("\n[场景4] 测试不同路径的CORS响应")
    paths = ["/", "/admin/", "/auth/get_user"]
    
    for path in paths:
        print(f"\n测试路径: {path}")
        try:
            headers = {"Origin": "http://example.com"}
            response = requests.get(f"{base_url}{path}", headers=headers)
            print(f"  状态码: {response.status_code}")
            print(f"  包含CORS头: {'Access-Control-Allow-Origin' in response.headers}")
        except Exception as e:
            print(f"  请求错误: {e}")

# 运行所有测试
if __name__ == "__main__":
    test_simple_get()
    test_options_preflight()
    test_credentials()
    test_different_paths()
    
    print("\n===== 测试完成 =====")
    print("请检查上面的测试结果，找出缺失的CORS头或配置问题。")